<template>
    <div class="device-manage">
        <a-card class="searchForm mb-twelve" style="border: none;">
            <a-form-model :model="searchForm" layout="inline" :colon="false" class="search-form">
              <a-form-model-item label="模糊搜索" prop="keyName" class="search-item">
                <a-input 
                  v-model="searchForm.keyName" 
                  placeholder="请输入关键字搜索"
                  style="width: 100%"
                />
              </a-form-model-item>
              <a-form-model-item class="action-item">
                <div class="action-buttons">
                  <a-button @click="search" type="primary">查询</a-button>
                  <a-button @click="reset" class="btn-reset">重置</a-button>
                </div>
              </a-form-model-item>
            </a-form-model>
          </a-card>
      <a-card style="background-color:#2C3360;border:none;">
        <div class="card-header">
            <div class="a-card-title">设备列表</div>
            <div class="action-group">
              <a-button type="danger" @click="del(null)" class="btn-danger">批量删除</a-button>
              <a-button @click="handleOpen('')" type="primary">添加</a-button>
            </div>
          </div>
        <div class="mb-sixteen">
          <!-- <a-table bordered :rowKey="record=>record.id"  :key="tableKey" :columns="columns"
            :data-source="normalizedList"  :loading="loading" :pagination="true" :scroll="{ x: 'max-content' }">
            <template slot="online_status"  slot-scope="text,record">
              <div v-if="record.online_status==0">离线</div>
              <div v-else style="color: #167ddc">在线</div>
            </template> -->
            <!-- 操作列模版 -->
            <!-- <template #actions="{record}">
                <span>
                  <a-button @click="handleGo(record)" type="link">设备详情</a-button>
                  <a-button @click="handleOpen(record)" type="link">编辑</a-button>
                  <a-button @click="configDeviceVisible = true" type="link">配置设备</a-button>
                  <a-button @click="configRulesVisible = true" type="link">配置规则</a-button>
                  <a-button @click="del(record)" type="link" danger>删除</a-button>
                </span>
            </template>
          </a-table> -->
          <a-table :columns="columns" :data-source="normalizedList">
            <template #headerCell="{ column }">
              <template v-if="column.key === 'name'">
                <span>
                  <smile-outlined />
                  Name
                </span>
              </template>
            </template>
        
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'name'">
                <a>
                  {{ record.name }}
                </a>
              </template>
              <template v-else-if="column.key === 'tags'">
                <span>
                  <a-tag
                    v-for="tag in record.tags"
                    :key="tag"
                    :color="tag === 'loser' ? 'volcano' : tag.length > 5 ? 'geekblue' : 'green'"
                  >
                    {{ tag.toUpperCase() }}
                  </a-tag>
                </span>
              </template>
              <template v-else-if="column.key === 'action'">
                <span>
                  <a-button @click="handleGo(record)" type="link">设备详情</a-button>
                  <!-- <a-button @click="handleOpen(record)" type="link">编辑</a-button>
                  <a-button @click="configDeviceVisible = true" type="link">配置设备</a-button>
                  <a-button @click="configRulesVisible = true" type="link">配置规则</a-button> -->
                  <a-button @click="del(record)" type="link" style="color: #F64646;">删除</a-button>
                </span>
              </template>
            </template>
          </a-table>
        </div>
        <div class="text-right" v-if="total > 0">
          <a-pagination :total="total" :current="searchForm.page" :page-size.sync="searchForm.pageSize"
            :page-size-options="$pageSizeOptions" @change="handlePageNo" @showSizeChange="showSizeChange"
            show-size-changer />
        </div>
      </a-card>
      <a-modal :title="title" 
        v-model="visible" 
        :maskClosable="false" 
        :width="830" centered 
        :footer="null"
        :destroyOnClose="true" >
        <a-spin :spinning="modalloading">
          <a-form-model ref="ruleForm" :model="form" :rules="rules" :colon="false" :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-model-item label="设备编号" prop="device_code">
                  <a-input v-model="form.device_code" placeholder="设备编号" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="设备名称" prop="device_name">
                  <a-input v-model="form.device_name" placeholder="请输入设备名称" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-model-item label="组织名称" prop="sensor_id">
                  <a-select v-model="form.sensor_id" placeholder="请选择组织" allowClear style="width:100%">
                    <a-select-option v-for="(item, index) in sessonsList" :value="item.id" :key="index">
                      {{ item.sensor_name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
  
              <a-col :span="12">
                <a-form-model-item label="MAC地址" prop="macAddr">
                  <a-input v-model="form.macAddr" placeholder="请输入MAC地址" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-model-item label="位置" prop="device_position">
                  <a-input v-model="form.device_position" placeholder="请输入位置" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="经度" prop="longitude">
                  <a-input v-model="form.longitude" placeholder="请输入经度" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-model-item label="纬度" prop="latitude">
                  <a-input v-model="form.latitude" placeholder="请输入纬度" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="设备类型" prop="device_type">
                  <a-input v-model="form.device_type" placeholder="请输入设备类型" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-model-item label="设备型号" prop="device_mode">
                  <a-input v-model="form.device_mode" placeholder="请输入设备型号" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="制造商" prop="device_factory">
                  <a-input v-model="form.device_factory" placeholder="请输入制造商" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="安装日期"  prop="install_time">
                  <a-date-picker v-model="form.install_time" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" placeholder="请选择安装日期" style="width: 100%;" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="24">
                <a-form-model-item label="描述" prop="describe" :label-col="{ span: 3 }" :wrapper-col="{ span: 20 }">
                  <a-textarea v-model="form.describe" placeholder="请输入描述" :autoSize="{ minRows: 4, maxRows: 6 }" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-spin>
        <div class="flex align-center justify-center">
          <a-button @click="visible = false"
            style="margin-left: 8px;background: #fff;color: #2C3360;border-color: #fff;margin-right: 15px">取消</a-button>
          <a-button @click="submit" type="primary">确定</a-button>
        </div>
      </a-modal>
  
      <a-modal title="配置设备" v-model="configDeviceVisible" :maskClosable="false" :width="510" centered :footer="null">
        <div>
          <a-form-model ref="ruleForm" :model="deviceForm" :rules="deviceRules" :colon="false" :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }">
                <a-form-model-item label="设备编号" prop="id">
                  <a-input v-model="deviceForm.id" placeholder="ID" disabled />
                </a-form-model-item>
                <a-form-model-item label="设备名称" prop="deviceName">
                  <a-input v-model="deviceForm.deviceName" placeholder="请输入设备名称" />
                </a-form-model-item>
                <a-form-model-item label="终端编码" prop="code">
                  <a-select v-model="deviceForm.code" placeholder="请选择终端编码" allowClear style="width:100%">
                    <a-select-option v-for="(item, index) in 2" :value="item" :key="index">
                      {{ item }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-form-model-item label="油品" prop="oils">
                  <a-select v-model="form.oils" placeholder="请选择油品" allowClear style="width:100%">
                    <a-select-option v-for="(item, index) in 2" :value="item" :key="index">
                      {{ item }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
          </a-form-model>
        </div>
        <div class="flex align-center justify-center">
          <a-button @click="configDeviceVisible = false"
            style="margin-left: 8px;background: #fff;color: #2C3360;border-color: #fff;margin-right: 15px">取消</a-button>
          <a-button @click="configDeviceVisible = false" type="primary">确定</a-button>
        </div>
      </a-modal>
      <a-modal title="配置规则" v-model="configRulesVisible" :maskClosable="false" :width="510" centered :footer="null">
        <div>
          <a-form-model ref="ruleForm" :model="rulesForm" :rules="rulesFormRules" :colon="false" :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }">
                <a-form-model-item label="设备编号" prop="id">
                  <a-input v-model="rulesForm.id" placeholder="ID" disabled />
                </a-form-model-item>
                <a-form-model-item label="设备名称" prop="deviceName">
                  <a-input v-model="rulesForm.deviceName" placeholder="请输入设备名称" />
                </a-form-model-item>
                <a-form-model-item label="规则" prop="rulesId">
                  <a-select v-model="rulesForm.rulesId" placeholder="请选择终规则" allowClear style="width:100%">
                    <a-select-option v-for="(item, index) in 2" :value="item" :key="index">
                      {{ item }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
  
          </a-form-model>
        </div>
        <div class="flex align-center justify-center">
          <a-button @click="configRulesVisible = false"
            style="margin-left: 8px;background: #fff;color: #2C3360;border-color: #fff;margin-right: 15px">取消</a-button>
          <a-button @click="configRulesVisible = false" type="primary">确定</a-button>
        </div>
      </a-modal>
    </div>
</template>

<script setup>
import {ref,onMounted,computed} from 'vue'
import { useRouter} from 'vue-router'
const router=useRouter()
const searchForm = ref({
  page: 1,
  pageSize: 15,
  keyName: ''
})
const total = ref(0)
const selectedRowKeys=ref([])
const list=ref([])
const title=ref('添加设备')
const modalloading=ref(false)

const handleOpen=(row)=>{
  modalloading.value=true
  form.value = { ...row } // 使用展开运算符
  visible.value = true
  title.value = row ? '编辑设备' : '添加设备'
  
  if (row) {
    form.value = { ...row } // 使用展开运算符
  } else {
    form.value = {
      device_code: '',
      device_name: '',
      sensor_id: undefined,
      // 补全其他表单字段初始值
    }
  }
}
const handleGo=(row)=>{
  router.push('/device/details')
}
const del = (record) => {
  // 实际删除逻辑需要对接后端API
  if (record?.id) {
    console.log('删除设备ID:', record.id)
    // 调用删除接口
    // await deleteDevice(record.id)
    // 刷新列表
    // await getList()
  } else if (selectedRowKeys.value.length) {
    console.log('批量删除IDs:', selectedRowKeys.value)
    // 调用批量删除接口
    // await batchDelete(selectedRowKeys.value)
    // 刷新列表
    // await getList()
  }
}

const columns = ref([
  {
    title: '设备名称',
    dataIndex: 'deviceName',
  },
  {
    title: '组织名称',
    dataIndex: 'organizationName',
  },
  {
    title: '设备类型',
    dataIndex: 'deviceType',
  },
  {
    title: '设备型号',
    dataIndex: 'deviceModel',
  },
  {
    title: '在线状态',
    dataIndex: 'online_status',
    scopedSlots: { customRender: 'online_status' },
  },
  {
    title: '操作',
    width:300,
    key:'action'
  }
])

const tableKey=ref(0)
const visible = ref(false)
const loading = ref(false)
const form = ref({
  device_code: '',
  device_name: '',
  sensor_id: undefined,
  macAddr: '',
  device_position: '',
  longitude: '',
  latitude: '',
  device_type: '',
  device_mode: '',
  device_factory: '',
  install_time: null,
  describe: ''
})
const rules=ref({
    sensor_id: [
          { required: true, message: '请选择组织', trigger: 'change' },
        ],
        device_position: [
          { required: true, message: '请输入位置', trigger: 'blur' },
        ],
        install_time: [
          { required: true, message: '请选择日期', trigger: 'change' },
        ]
})
const sessonsList=ref([])
const configDeviceVisible=ref(false)
const deviceForm=ref({})
const deviceRules=ref({
    deviceName: [
          { required: true, message: '请输入设备名称', trigger: 'blur' },
        ],
        code: [
          { required: true, message: '请选择终端编码', trigger: 'change' },
        ],
})
const rulesForm=ref({
    rulesId:undefined
})
const rulesFormRules=ref({
    deviceName: [
          { required: true, message: '请输入设备名称', trigger: 'blur' },
        ],
        rulesId: [
          { required: true, message: '请选择终规则', trigger: 'change' },
        ],
})

onMounted(async()=>{
  await getList()
//   console.log('原始数据:', list.value);
  //console.log('处理后数据:', normalizedList.value);
})
const getList=async()=>{    
    loading.value=false;
    var response=await fetch('/api/device/getdevicelist');
    var res = await response.json();
    list.value=res.data.list;
    total.value=res.data.total || 0
    tableKey.value++;
}   
const normalizedList=computed(()=>{
    return list.value.map((item,index)=>({
            ...item,
            online_status:item.online_status==1?'在线':'离线'
        }))
})


</script>

<style scoped lang="less">
.device-manage{
    background: #1A1F4D !important ; // 设置基础背景色
    padding: 20px;       // 添加呼吸空间
    min-height: 100vh;   // 确保高度撑开
}
:deep(.ant-pagination-prev) .ant-pagination-item-link,
.ant-pagination-next .ant-pagination-item-link {
  background-color: #42487A;
  border-color: #999da0;
  color: #898a94;
}

:deep(.ant-pagination-next) .ant-pagination-item-link {
  background-color: #42487A;
  border-color: #999da0;
  color: #898a94;
}

:deep( .ant-pagination-item) {
  background-color: #42487A;
  border-color: #999da0;

}

:deep( .ant-pagination-item) a {
  color: #898a94;
}

:deep(.ant-pagination-item-active) {
  border-color: #fff;
}

:deep(.ant-pagination-item-active) a {
  color: #fff;
}

:deep(.ant-select-selection) {
  background-color: #42487A;
  border-color: #999da0;
  color: #898a94;
}

:deep(.ant-btn-link) {
  color: #DADDED;
}
.searchForm{
    background: #2C3360;
    margin: 10px auto;
}
.search-form {
    display: flex;
    gap: 16px; // 表单项间距
    
    .search-item {
      flex: 1; // 占据剩余空间
      margin: 0;
      
      // 输入框容器
      :deep(.ant-form-item-control-wrapper) {
        width: 100%;
      }
    }
  
    .action-item {
      flex-shrink: 0; // 禁止收缩
      margin: 0;
      
      .action-buttons {
        display: flex;
        gap: 8px;
        
        .ant-btn {
          white-space: nowrap;
        }
      }
    }
  }
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    margin: 10px auto;
    
    .a-card-title {
      flex: 1;
      white-space: nowrap;
      margin-right: 16px;
      color: #fff;
    }
  
    .action-group {
      flex-shrink: 0;
      display: flex;
      gap: 8px;
    }
  }
  // 在<style>区块添加以下内容
  :deep(.ant-table) {
    background: #2C3360;
    border: none;

    // 表格头部
    .ant-table-thead > tr > th {
      background: #363E71;
      border-color: #454d83;
      color: #DADDED;
      border: none;
      &::before{
        display: none;;
      }
    }
  
    // 表格主体
    .ant-table-tbody {
      background: #2C3360;
      border: none;
      
      // 表格行
      > tr {
        background: #2C3360;
        border-color: #454d83;
        
        // 文字颜色
        > td {
          color: #DADDED;
          border-color: #454d83;
        }
        >tr >td {
            border: none !important;
        }
        // 行间分隔线
        > tr:not(:last-child) > td {
          border-bottom: 1px solid #454d83; // 保留浅色分隔线(可选)
        }
  
        // 悬停效果
        &:hover td {
          background: #363E71 !important;
        }
      }
    }
    // 去除表格容器边框
  .ant-table-container {
    border: none !important;
  }
}
</style>